package com.weather.net;

import android.util.Log;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by sunshine on 2017/3/7.
 */

public class NetRequest {
    private static final String TAG = "====NetRequest====";
    private static NetRequest netRequest;
    public static NetRequest getInstance(){
        if (netRequest == null){
            synchronized (NetRequest.class){
                if (netRequest == null){
                    netRequest = new NetRequest();
                }
            }
        }
        return netRequest;
    }
    private OkHttpClient client;
    private Retrofit retrofit;
    private NetRequest(){
        client = getClient();
        retrofit = getRetrofit();
    }

    public OkHttpClient getClient() {
        HttpLoggingInterceptor log = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.e(TAG,message);
            }
        });
        log.setLevel(HttpLoggingInterceptor.Level.BODY);
        return new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20,TimeUnit.SECONDS)
                .writeTimeout(20,TimeUnit.SECONDS)
                .addInterceptor(log)
                .build();
    }

    private Retrofit getRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(NetConfig.BASE_URL)
                .client(client)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    private IApi api;
    public IApi getApi(){
        if (api == null){
            api = retrofit.create(IApi.class);
        }
        return api;
    }
}
